//
//  UserCenter.m
//  ObjcGo
//
//  Created by 邢伟新 on 2021/3/16.
//

#import "UserCenter.h"



static UserCenter *manager = nil;

@interface UserCenter ()<NSMutableCopying,NSCopying>

@property(nonatomic,strong)NSMutableDictionary *dataDic;
@property(nonatomic,strong)dispatch_queue_t concurrent_queue;

@end

@implementation UserCenter


+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]init];
    
    });
    return manager;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        
        self.dataDic = [[NSMutableDictionary alloc]init];
        self.concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
        
        
    }
    return self;
}


+ (id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [super allocWithZone:zone];
    });
    return manager;
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
    return manager;
}

- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {
    return manager;
}


- (void)setObject:(id)obj forKey:(NSString *)key{
    
//    dispatch_async(self.concurrent_queue, ^{
//
//        [self.dataDic setObject:obj forKey:key];
//
//        NSLog(@"write:%@",[NSThread currentThread]);
//
//
//    });
    
    dispatch_barrier_sync(self.concurrent_queue, ^{
        
        [self.dataDic setObject:obj forKey:key];
        
        NSLog(@"write:%@",[NSThread currentThread]);
        
        
    });
    
}


- (id)objectForKey:(NSString *)key
{
    __block id obj;
    // 同步读取指定数据
    dispatch_async(self.concurrent_queue, ^{
        obj = [self.dataDic objectForKey:key];
        
        NSLog(@"read:%@",[NSThread currentThread]);
    });
    
    return obj;
}





@end
